package cn.gdchent.springbootsecurity.authentication;

import cn.gdchent.springbootsecurity.enity.UserInfoDetails;
import cn.gdchent.springbootsecurity.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @auther:gdchent
 * @create:2020/4/20 10:57
 * @Description:https://zhuanlan.zhihu.com/p/47395352
 */
@Component
public class BackdoorAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    @Qualifier(value = "userDetailsServiceImpl")
    private UserDetailsServiceImpl userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("auth:"+authentication.toString());
        String name=authentication.getName();
        System.out.println("authenticate:"+name);
        String password= (String) authentication.getCredentials();
        System.out.println("password:"+password);
        UserInfoDetails userInfoDetails = (UserInfoDetails) userDetailsService.loadUserByUsername(name);
        if(name.equals("user")){//用户名
            Collection<GrantedAuthority> authorityCollection=new ArrayList<>();
            authorityCollection.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new UsernamePasswordAuthenticationToken(
                    userInfoDetails,password,authorityCollection);
        }else if(name.equals("admin")){ //用户
            Collection<GrantedAuthority> authorityCollection=new ArrayList<>();
            authorityCollection.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            authorityCollection.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new UsernamePasswordAuthenticationToken(
                    userInfoDetails,password,authorityCollection);
        }
        //https://blog.csdn.net/qq_39620552/article/details/83094600
        return new UsernamePasswordAuthenticationToken(userInfoDetails, userInfoDetails.getPassword(), userInfoDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
